package com.yanfan.parking.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.yanfan.ibms.common.utils.HttpUtils2;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

public class OauthUtil {
    public static void main(String[] args) {
        OauthUtil oauthUtil = new OauthUtil();
        oauthUtil.getPublicKey();
    }

    /**
     * 获取RestTemplate实例
     * @return RestTemplate实例
     */
    public static RestTemplate getRestTemplate() {
        RestTemplate restTemplate = null;
        try {
            // 创建一个信任所有证书的 SSL 上下文
            SSLContext sslContext = new SSLContextBuilder()
                    .loadTrustMaterial(null, (chain, authType) -> true)
                    .build();

            // 创建一个忽略主机名验证的 SSL 连接套接字工厂
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

            // 创建 HttpClient
            CloseableHttpClient httpClient = HttpClients.custom()
                    .setSSLSocketFactory(sslsf)
                    .build();

            // 创建 ClientHttpRequestFactory
            ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);

            // 创建 RestTemplate 并设置请求工厂
            restTemplate = new RestTemplate(requestFactory);

        } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return restTemplate;
    }

    /**
     * 获取公钥
     * @return 公钥字符串
     */
    /**
     * 获取公钥
     * @return 公钥字符串
     */
    public static String getPublicKey() {
        try {
            ResponseEntity<String> response = getRestTemplate()
                    .getForEntity("https://192.168.254.6:443/evo-apigw/evo-oauth/1.0.0/oauth/public-key", String.class);

            // 假设返回的数据是一个 Map，转成 JSON 字符串
            Map<String, Object> data = JSON.parseObject(response.getBody(), Map.class);
            String json = JSON.toJSONString(data);
            JSONObject jsonObject = JSONObject.parseObject(json);
            Object data1 = jsonObject.get("data");
            JSONObject jsonData = JSONObject.parseObject(data1.toString());

            //System.out.println(jsonData.get("publicKey").toString()); // 打印 JSON 数据
            return jsonData.get("publicKey").toString();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取access_token
     */
    public static String accessToken(String publicKey) throws Exception {
        String encrypt = RSAUtil.encrypt("Admin123", publicKey);
        HashMap<String, Object> param = new HashMap<>();
        param.put("grant_type","password");
        param.put("username","system");
        param.put("password",encrypt);
        param.put("client_id","OpenAPI");
        param.put("client_secret","916d26dc-fe7f-4480-ad6c-7648c3a13da8");
        param.put("public_key",publicKey);
        HashMap<String, String> headers = new HashMap<>();
        JSONObject jsonObject = HttpUtils2.
                sendPostSSLBody("https://192.168.254.6:443/evo-apigw/evo-oauth/1.0.0/oauth/extend/token"
                        ,null,param);
        System.out.println(jsonObject);
        Object data = jsonObject.get("data");
        String access_token = JSONObject.parseObject(data.toString()).get("access_token").toString();
        return access_token;
    }

}